/**
 * NUM 数字
 * SMALL_LETTER 小写字母
 * CAPITAL_LETTER 大写字母
 * OTHER_CHAR 特殊字符
 */
const NUM = 1;
const SMALL_LETTER = 2;
const CAPITAL_LETTER = 3;
const OTHER_CHAR = 4;

// 判断是否含有大写字母
function hasCapital(str) {
    let result = str.match(/^.*[A-Z]+.*$/);
    if (result == null) return false;
    return true;
}

// 判断是否含有小写字母
function hasLowercase(str) {
    let result = str.match(/^.*[a-z]+.*$/);
    if (result == null) return false;
    return true;
}

// 判断是否含有数字
function hasNumber(str) {
    let result = str.match(/^.*[0-9]+.*$/);
    if (result == null) return false;
    return true;
}

// 判断是否含有其他字符
function hasOther(str) {
    let result = str.match(/^.*[^0-9A-Za-z]+.*$/);
    if (result == null) return false;
    return true;
}

function checkCharacterType(str) {

}

exports.checkPasswordStrength = function (password) {
    if (!password) {
        return false;
    }
    if (Object.prototype.toString.call(password) != '[object String]') {
        return false;
    }
    if (password.length < 8 || password.length > 20) {
        return false;
    }
    let num = false;
    let smallLetter = false;
    let capitalLetter = false;
    let otherChar = false;

    for (let i = 0; i < password.length; i++) {
        if (hasCapital(password.charAt(i))) {
            capitalLetter = true;
        }
        else if (hasLowercase(password.charAt(i))) {
            smallLetter = true;
        }
        else if (hasNumber(password.charAt(i))) {
            num = true;
        } else {
            otherChar = true;
        }
    }
    let count = 0;
    if (num) {
        count++;
    }
    if (smallLetter) {
        count++;
    }
    if (capitalLetter) {
        count++;
    }
    if (otherChar) {
        count++;
    }
    return count >= 2;
};

function getRandom(min, max) {
    return Math.round(Math.random() * (max - min) + min)
}

exports.randomPassword = function (len) {
    let code = '';
    for (var i = 0; i < len; i++) {
        var type = getRandom(1, 3)
        switch (type) {
            case 1:
                code += String.fromCharCode(getRandom(48, 57));// 数字
                break;
            case 2:
                code += String.fromCharCode(getRandom(65, 90));// 大写字母
                break;
            case 3:
                code += String.fromCharCode(getRandom(97, 122));// 小写字母
                break;
            default:
                code += String.fromCharCode(getRandom(97, 122));// 小写字母
                break;
        }
    }
    return code
};
